package com.ambimmort.shj.service.logmanageService;

import cn.net.greenet.common.db_service.BaseDao;
import cn.net.greenet.db.bean.Systemproperty;
import cn.net.greenet.device.td.TdLogService;
import cn.net.greenet.logmanage.logic.LogManageService;
import cn.net.greenet.logmanage.logic.bean.*;
import cn.net.greenet.logmanage.logic.common.*;
import cn.net.greenet.logmanage.nn.*;
import cn.net.greenet.logmanage.servlet.QueryStrategySend;
import com.ambimmort.shj.action.logmanage.nn.*;
import com.ambimmort.shj.action.logmanage.nn.DBUtils;
import com.ambimmort.shj.action.logmanage.nn.QueryReceiveLog;
import com.ambimmort.umessage.UcMsg;
import com.ambimmort.umessage.util.HexUtil;
import com.j256.ormlite.support.ConnectionSource;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Blob;
import java.sql.ResultSet;
import java.text.ParseException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by ma on 2015/7/30.
 */
@Service
public class LogmanageService {
//
//    @Autowired
//    private SessionFactory hibernateSessionFactory;

    ResultSet rs = null;
    BaseDao baseDao = null;

    private void init() {
        baseDao = new BaseDao();
    }

    private void close() {
        if (baseDao != null) {
            baseDao.close();
        }
    }

    /**
     * @param logId
     * @return
     */
    public String messageincominglogView(String logId) {
        init();
        String sql = "select * from Messageincominglog where id=?";
        Object[] p = {logId};
        JSONObject obj = new JSONObject();
        try {
            rs = baseDao.executeSQL(sql, p);
            if (rs.next()) {
                String messageType = rs.getString("messageType");
                byte[] packet = rs.getBytes("packet");
                UcMsg msg = UcMsg.create(messageType);
                obj.put("bin", HexUtil.getHex(packet));
                try {
                    msg.parseBinary(packet);
                } catch (Exception e) {
                    obj.put("json", new String(Base64.encodeBase64("message content error".getBytes("utf-8")), "utf-8"));
                }
                obj.put("json", new String(Base64.encodeBase64(msg.toJSON().getBytes("utf-8")), "utf-8"));
            }
//        Session session = hibernateSessionFactory.openSession();
//        JSONObject obj = new JSONObject();
//        try {
//            Messageincominglog log = (Messageincominglog) session.get(Messageincominglog.class, Long.parseLong(logId));
//            UcMsg msg = UcMsg.create(log.getMessageType());
//            obj.put("bin", HexUtil.getHex(log.getPacket()));
//            try {
//                msg.parseBinary(log.getPacket());
//            } catch (Exception e) {
//                obj.put("json", new String(Base64.encodeBase64("message content error".getBytes("utf-8")), "utf-8"));
//            }
//            obj.put("json", new String(Base64.encodeBase64(msg.toJSON().getBytes("utf-8")), "utf-8"));
//
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            session.close();
            close();
        }
        return obj.toString();
    }

    /**
     * @param logId
     * @param type
     * @return
     */
    public String messageoutgoinglog_auto_View(String logId, String type) {

        init();
        String sql = "select * from Messageincominglog where id=?";
        Object[] p = {logId};
        JSONObject obj = new JSONObject();
        try {
            rs = baseDao.executeSQL(sql, p);
            if (rs.next()) {
                String messageType = rs.getString("messageType");
                byte[] packet = rs.getBytes("packet");
                UcMsg msg = UcMsg.create(messageType);
                obj.put("bin", HexUtil.getHex(packet));
                try {
                    msg.parseBinary(packet);
                    obj.put("json", new String(Base64.encodeBase64(msg.toJSON().getBytes("utf-8")), "utf-8"));
                } catch (Exception e) {
                    e.printStackTrace();
                    obj.put("json", new String(Base64.encodeBase64("message content error".getBytes("utf-8")), "utf-8"));
                }
            }

//        Session session = hibernateSessionFactory.openSession();
//        JSONObject obj = new JSONObject();
//        try {
//            Messageoutgoinglog log = (Messageoutgoinglog) session.get(Messageoutgoinglog.class, Long.parseLong(logId));
//            UcMsg msg = UcMsg.create(log.getMessageType());
//            obj.put("bin", HexUtil.getHex(log.getPacket()));
//            try {
//                msg.parseBinary(log.getPacket());
//                obj.put("json", new String(Base64.encodeBase64(msg.toJSON().getBytes("utf-8")), "utf-8"));
//            } catch (Exception e) {
//                e.printStackTrace();
//                obj.put("json", new String(Base64.encodeBase64("message content error".getBytes("utf-8")), "utf-8"));
//            }
//
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close();
//            session.close();
        }
        return obj.toString();
    }

    /**
     * @param logId
     * @param type
     * @return
     */
    public String messageoutgoinglog_manaul_View(String logId, String type) {

        init();
        String sql = "select * from Messageoutgoinglog_Manual where id=?";
        Object[] p = {logId};
        JSONObject obj = new JSONObject();
        try {
            rs = baseDao.executeSQL(sql, p);
            if (rs.next()) {
                String messageType = rs.getString("messageType");
                System.out.println("AAAAAA:" + messageType);
                byte[] packet = rs.getBytes("packet");
                UcMsg msg = UcMsg.create(messageType);
                obj.put("bin", HexUtil.getHex(packet));
                try {
                    msg.parseBinary(packet);
                    obj.put("json", new String(Base64.encodeBase64(msg.toJSON().getBytes("utf-8")), "utf-8"));
                } catch (Exception e) {
                    e.printStackTrace();
                    obj.put("json", new String(Base64.encodeBase64("message content error".getBytes("utf-8")), "utf-8"));
                }
            }
//        Session session = hibernateSessionFactory.openSession();
//        JSONObject obj = new JSONObject();
//        try {
//            MessageoutgoinglogManual log = (MessageoutgoinglogManual) session.get(MessageoutgoinglogManual.class, Long.parseLong(logId));
//            System.out.println("AAAAAA:" + log.getMessageType());
//            UcMsg msg = UcMsg.create(log.getMessageType());
//            obj.put("bin", HexUtil.getHex(log.getPacket()));
//            try {
//                msg.parseBinary(log.getPacket());
//                obj.put("json", new String(Base64.encodeBase64(msg.toJSON().getBytes("utf-8")), "utf-8"));
//            } catch (Exception e) {
//                e.printStackTrace();
//                obj.put("json", new String(Base64.encodeBase64("message content error".getBytes("utf-8")), "utf-8"));
//            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close();
//            session.close();
        }
        return obj.toString();
    }


    public String queryDeviceService() {
        ConnectionSource conn = null;
        try {
            conn = DBUtils.getConnectionSource();
            LogManageService service = new LogManageService(conn);
            List<DPIEndPointBean> beans = service.getDeviceList();

            JSONArray devices = new JSONArray();
            if (beans != null) {
                Iterator<DPIEndPointBean> it = beans.iterator();
                while (it.hasNext()) {
                    DPIEndPointBean bean = it.next();
                    JSONObject o = new JSONObject();
                    o.put("id", bean.getId());
                    o.put("name", bean.getName());
                    o.put("ip", bean.getMasterIp());
                    o.put("isCCOn", bean.isClientChannelConnected() ? 1 : 0);
                    o.put("isSCOn", bean.isServerChannelConnected() ? 1 : 0);

                    devices.add(o);
                }
            }
            return devices.toString();
        } catch (Exception ex) {
            return "[]";
        } finally {
            DBUtils.closeConnectionSource(conn);
        }
    }

    /**
     * @param id             设备
     * @param startTime
     * @param endTime
     * @param MessageType    optional
     * @param MessageNo      optional
     * @param iDisplayStart  查询的起始条数
     * @param iDisplayLength 每页显示的条数
     * @return returnJson
     */
    public String queryPolicyReceiveLog(String id, String startTime, String endTime, String MessageType,
                                        String MessageNo, String iDisplayStart, String iDisplayLength) {
        String returnJson = QueryReceiveLog.query(iDisplayStart, iDisplayLength, id, startTime, endTime, MessageType, MessageNo);

        return returnJson;

    }

    /**
     * @param id             设备
     * @param startTime
     * @param endTime
     * @param MessageType    optional
     * @param MessageNo      optional
     * @param sendType
     * @param iDisplayStart  查询的起始条数
     * @param iDisplayLength 每页显示的条数
     * @return
     */
    public String queryPolicySendLog(String id, String startTime, String endTime, String MessageType,
                                     String MessageNo, String sendType, String iDisplayStart, String iDisplayLength) {

        String returnJson = "";
        if ("0".equals(sendType)) {
            try {
                System.out.println("auto++++++");
                returnJson = QuerySendPolicyAuto.query(iDisplayStart, iDisplayLength, id, startTime, endTime, MessageType, MessageNo);
            } catch (ParseException ex) {
                Logger.getLogger(QueryPolicySendLog.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            returnJson = cn.net.greenet.logmanage.nn.QuerySendPolicyHand.query(iDisplayStart, iDisplayLength, id, startTime, endTime, MessageType, MessageNo);
        }
        return returnJson;
    }

    /**
     * @param deviceId
     * @param startTime
     * @param endTime
     * @param pageCount
     * @param page
     * @param MessageType
     * @param MessageNo
     * @param ip
     * @param rck_flag
     * @return
     */
    public String queryStrategyReceive(String deviceId, long startTime, long endTime, int pageCount, int page, String MessageType
            , String MessageNo, String ip, String rck_flag) {
        ConnectionSource conn = null;
        try {
            JSONArray outputData = new JSONArray();
            conn = cn.net.greenet.logmanage.logic.common.DBUtils.getConnectionSource();
            LogManageService service = new LogManageService(conn);
            Map<MessageInComingLogBean, AckOutGoingLogBean> logs = null;
            if (deviceId != null) {
                int id = Integer.parseInt(deviceId);
                logs = service.getStrategyReceiveLogByDeviceId(id, startTime, endTime, pageCount, page, MessageType, MessageNo);
            } else if (ip != null) {
                logs = service.getStrategyReceiveLogByDeviceIP(ip, startTime, endTime, pageCount, page, MessageType, MessageNo);
            } else {
                throw new Exception("parameter id or ip are not provided");
            }
            if (logs != null) {
                Iterator<Map.Entry<MessageInComingLogBean, AckOutGoingLogBean>> it = logs.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<MessageInComingLogBean, AckOutGoingLogBean> entry = it.next();
                    MessageInComingLogBean message = entry.getKey();
                    AckOutGoingLogBean ack = entry.getValue();

                    JSONObject o = new JSONObject();
                    o.put("id", message.getDpi().getId());
                    o.put("MessageType", message.getMessageType());
                    o.put("MessageNo", message.getMessageNo());
                    o.put("MessageSequenNo", message.getMessageSequenceNo());
                    o.put("MessageSerialNo", message.getMessageSerialNo());
                    o.put("MessageAckFlag", ack == null ? 0 : 1);
                    o.put("name", message.getDpi().getName());
                    if (ack != null) {
                        o.put("rckSendTime", ack.getSendTime().getTime() / 1000);
                    }
                    outputData.add(o);
                }
            }
            return outputData.toString();
        } catch (Exception ex) {
            Logger.getLogger(QueryStrategySend.class.getName()).log(Level.SEVERE, null, ex);
            return "[]";
        } finally {
            cn.net.greenet.logmanage.logic.common.DBUtils.closeConnectionSource(conn);
        }
    }

    /**
     * @param deviceId
     * @param startTime
     * @param endTime
     * @param pageCount
     * @param page
     * @param MessageType
     * @param MessageNo
     * @param ip
     * @param rck_flag
     * @return
     */

    public String queryStrategySend(String deviceId, long startTime, long endTime, int pageCount, int page, String MessageType
            , String MessageNo, String ip, String rck_flag) {
        ConnectionSource conn = null;
        try {
            JSONArray outputData = new JSONArray();
            conn = cn.net.greenet.logmanage.logic.common.DBUtils.getConnectionSource();
            LogManageService service = new LogManageService(conn);
            Map<MessageOutGoingLogBean, AckInComingLogBean> logs = null;
            if (deviceId != null) {
                int id = Integer.parseInt(deviceId);
                logs = service.getStrategySendLogByDeviceId(id, startTime, endTime, pageCount, page, MessageType, MessageNo);
            } else if (ip != null) {
                logs = service.getStrategySendLogByDeviceIP(ip, startTime, endTime, pageCount, page, MessageType, MessageNo);
            } else {
                throw new Exception("parameter id or ip are not provided");
            }
            if (logs != null) {
                Iterator<Map.Entry<MessageOutGoingLogBean, AckInComingLogBean>> it = logs.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<MessageOutGoingLogBean, AckInComingLogBean> entry = it.next();
                    MessageOutGoingLogBean message = entry.getKey();
                    AckInComingLogBean ack = entry.getValue();

                    JSONObject o = new JSONObject();
                    o.put("id", message.getDpi().getId());
                    o.put("MessageType", message.getMessageType());
                    o.put("MessageNo", message.getMessageNo());
                    o.put("MessageSequenNo", message.getMessageSequenceNo());
                    o.put("MessageSerialNo", message.getMessageSerialNo());
                    o.put("MessageAckFlag", ack == null ? 0 : 1);
                    o.put("name", message.getDpi().getName());
                    if (ack != null) {
                        o.put("rckReceiveTime", ack.getReceiveTime().getTime() / 1000);
                    }
                    o.put("sendStartTime", message.getSendStartTime().getTime() / 1000);
                    o.put("sendStopTime", message.getSendStopTime().getTime() / 1000);
                    outputData.add(o);
                }
            }
            return outputData.toString();
        } catch (Exception ex) {
            Logger.getLogger(com.ambimmort.shj.action.logmanage.QueryStrategySend.class.getName()).log(Level.SEVERE, null, ex);
            return "[]";
        } finally {
            cn.net.greenet.logmanage.logic.common.DBUtils.closeConnectionSource(conn);
        }
    }

    /**
     * @param json
     * @param username
     * @param starttime
     * @param endtime
     * @param iDisplayStart
     * @param iDisplayLength
     * @return
     */
    public String queryUserOperation(String json, String username, String starttime, String endtime,
                                     String iDisplayStart, String iDisplayLength) {

        JSONObject jo = JSONObject.fromObject(json);

        return jo.toString();
    }


    public String setListProperty(String property) {

//        Session session = hibernateSessionFactory.openSession();
//        session.clear();
//        Transaction tx = session.beginTransaction();

        init();
        JSONArray jsonArr = JSONArray.fromObject(property);
        JSONObject jo;
        try {
            for (int i = 0; i < jsonArr.size(); i++) {
                jo = jsonArr.getJSONObject(i);
                for (Object key : jo.keySet()) {
                    String sql = "select property from Systemproperty";
                    Object[] p = {key};
                    if (rs.next()) {
                        rs = baseDao.executeSQL(sql, p);
                    }
//                    systemProperty = (Systemproperty) session.get(Systemproperty.class, key.toString());
//                    systemProperty.setValue(jo.getString(key.toString()));
//                    session.update(systemProperty);
                }
            }
//            tx.commit();
            return "{\"result\":\"true\"}";
//            out.println("{\"result\":\"true\"}");
        } catch (Exception e) {
            e.printStackTrace();
//            tx.rollback();
            return "{\"result\":\"false\"}";
//             out.println("{\"result\":\"false\"}");
        } finally {
            close();
//            session.close();
        }
    }

    public String tdLogQuery(String ip, String user) {

        if (ip.equals("")) {
            ip = null;
        }
        if (user.equals("")) {
            user = null;
        }
        System.out.println("ip:" + ip + " " + (ip == null) + ", user:" + user + " " + (user == null));

        TdLogService tds = new TdLogService();
        JSONArray arr = null;
        if (ip == null && user == null) {
            arr = tds.queryAll();
        } else if (ip == null) {
            arr = tds.queryBYUSER(user);
        } else if (user == null) {
            arr = tds.queryBYTP(ip);
        } else {
            arr = tds.searchTdLog(ip, user);
        }
        return arr.toString();
    }
}

